<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import { onMounted, onUnmounted, ref } from 'vue'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { io, type Socket } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType } from '@/enums'

const store = useUserStore()
const route = useRoute()

let socket: Socket
let list = ref<Message[]>([])
onMounted(async () => {
  // 建立链接，创建 socket.io 实例
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })

  socket.on('connect', () => {
    // 建立连接成功
    console.log('connect')
  })

  socket.on('error', (error) => {
    // 错误异常消息
    console.log('出错了！', error)
  })

  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('disconnect')
  })
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    const mesArr: Message[] = []
    data.forEach((mes) => {
      // 发送消息的时间
      mesArr.push({
        id: mes.createTime,
        msgType: MsgType.Notify,
        createTime: mes.createTime,
        msg: {
          content: mes.createTime
        }
      })
      // 发送的消息
      mesArr.push(...mes.items)
    })
    list.value.push(...mesArr)
    console.log(list)
  })
})

onUnmounted(() => {
  socket.close()
})
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室" />
    <!-- 1. 问诊状态：未接诊|咨询中|问诊结束-->
    <room-status />
    <!-- 2. 问诊聊天列表消息 -->
    <room-message :list="list" />
    <!-- 3. 底部操作栏：发消息 -->
    <room-action />
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
